import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const token = ref(localStorage.getItem('token') || null)
  const user = ref(null)
  const isAuthenticated = ref(!!token.value)

  // 动作
  const setToken = (newToken) => {
    token.value = newToken
    isAuthenticated.value = !!newToken
    
    if (newToken) {
      localStorage.setItem('token', newToken)
    } else {
      localStorage.removeItem('token')
    }
  }

  const setUser = (userData) => {
    user.value = userData
    if (userData) {
      localStorage.setItem('user', JSON.stringify(userData))
    } else {
      localStorage.removeItem('user')
    }
  }

  const logout = () => {
    setToken(null)
    setUser(null)
    isAuthenticated.value = false
    
    // 清除所有相关的localStorage数据
    localStorage.removeItem('token')
    localStorage.removeItem('user')
    
    // 通过window.location跳转，避免循环依赖
    window.location.href = '/login'
  }

  const initializeAuth = () => {
    // 从localStorage恢复用户状态
    const savedToken = localStorage.getItem('token')
    const savedUser = localStorage.getItem('user')
    
    if (savedToken) {
      token.value = savedToken
      isAuthenticated.value = true
    }
    
    if (savedUser) {
      try {
        user.value = JSON.parse(savedUser)
      } catch (error) {
        console.error('解析用户数据失败:', error)
        localStorage.removeItem('user')
      }
    }
  }

  // 检查token是否过期（简单检查）
  const isTokenValid = () => {
    if (!token.value) return false
    
    try {
      // 如果使用JWT，可以解析token检查过期时间
      // 这里简单返回true，实际项目中应该检查token有效性
      return true
    } catch (error) {
      return false
    }
  }

  // 初始化时恢复认证状态
  initializeAuth()

  return {
    // 状态
    token,
    user,
    isAuthenticated,
    
    // 动作
    setToken,
    setUser,
    logout,
    initializeAuth,
    isTokenValid
  }
}, {
  persist: {
    // 可选：使用pinia-plugin-persistedstate进行持久化
    key: 'auth-store',
    storage: localStorage,
    paths: ['token', 'user']
  }
}) 